﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using VSM.Admin.DAO;

namespace VSM
{
    public partial class SystemProcedureSecurity : System.Web.UI.Page
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
           /* if (Session[Utils.AppConstants.UserCode] == null
             || Session[Utils.AppConstants.CompanyName] == null
             || Session[Utils.AppConstants.CompanyCode] == null
              || Session[Utils.AppConstants.OutletCode] == null
                || Session[Utils.AppConstants.OutletName] == null
               || Session[Utils.AppConstants.IsSupperUser] == null
              || Session[Utils.AppConstants.Password] == null)
            {
                Response.Redirect("Login.aspx");
            }*/
            try
            {
                /*if (System.Configuration.ConfigurationManager.AppSettings["HoldingDatabase"].ToString() != Session[VSM.Utils.AppConstants.CompanyCode].ToString())
                {
                    Response.Redirect("Homepage.aspx");
                }*/
                if (!IsPostBack)
                {
                    LoadGroup(""); // param is ID Dealer
                    LoadItem(""); // param is ID Dealer
                }
            }
            catch (Exception ex)
            {
                string alert = "alert('Error:" + ex.Message.Replace('\'', ' ') + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "LoadItem", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvSearchResult_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvFunction.PageIndex = e.NewPageIndex;
            //LoadOutletSupplier(this.drdOutlet.SelectedValue.ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadItem(string aID_Dealer)
        {
            DataTable tb = new DataTable();
            tb.Columns.Add("ID_Module");
            tb.Columns.Add("ID_Object");
            tb.Columns.Add("ID_Group");
            tb.Columns.Add("ID_Dealer");

            tb.Columns.Add("Read_Access");
            tb.Columns.Add("Add_Access");
            tb.Columns.Add("Delete_Access");
            tb.Columns.Add("Modify_Access");
            tb.Columns.Add("Print_Access");

            BindItem(tb, aID_Dealer);
        }
        /// <summary>
        /// 
        /// </summary>
        private void LoadGroup(string aID_Dealer)
        {
            DataSet dsGroup = null;
            try
            {
                if(string.IsNullOrEmpty(aID_Dealer))
                    dsGroup = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_Group From tbl_Groups");
                else
                    dsGroup = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ID_Group From tbl_Groups Where ID_Dealer = '" + aID_Dealer + "'");

                lstUserGroup.DataSource = dsGroup.Tables[0];
                lstUserGroup.DataValueField = "ID_Group";
                lstUserGroup.DataTextField = "ID_Group";
                lstUserGroup.DataBind();

                if (lstUserGroup.Items.Count > 0) lstUserGroup.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "LoadGroup()", alert, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void BindItem(DataTable tb, string aID_Dealer)
        {
            try
            {
                DataSet dsObjectsGroups = null;
                if(string.IsNullOrEmpty(aID_Dealer))
                    dsObjectsGroups = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ObjGrp.Read_Access, ObjGrp.Add_Access, ObjGrp.Delete_Access, "
                        + " ObjGrp.Modify_Access, ObjGrp.Print_Access, ObjGrp.Post_Access, ObjGrp.CloseOpenDoc_Access, ObjGrp.Object_ID_Language, ObjGrp.ID_Module, "
                        + " ObjGrp.ID_Object, Obj.[Description], ObjGrp.ID_Group, ObjGrp.ID_Dealer, ObjGrp.CreatedUser, ObjGrp.CreatedTime, ObjGrp.UpdatedUser, ObjGrp.UpdatedTime "
                        + " From tbl_Objects Obj inner join tbl_ObjectsGroups ObjGrp ON Obj.ID_Object = ObjGrp.ID_Object "
                        + " Where ObjGrp.ID_Group = '" + lstUserGroup.SelectedValue + "'");
                else
                    dsObjectsGroups = SqlHelper.ExecuteDataSet(Data.ConnectionString, CommandType.Text, "Select ObjGrp.Read_Access, ObjGrp.Add_Access, ObjGrp.Delete_Access, "
                        + " ObjGrp.Modify_Access, ObjGrp.Print_Access, ObjGrp.Post_Access, ObjGrp.CloseOpenDoc_Access, ObjGrp.Object_ID_Language, ObjGrp.ID_Module, "
                        + " ObjGrp.ID_Object, Obj.[Description], ObjGrp.ID_Group, ObjGrp.ID_Dealer, ObjGrp.CreatedUser, ObjGrp.CreatedTime, ObjGrp.UpdatedUser, ObjGrp.UpdatedTime "
                        + " From tbl_Objects Obj inner join tbl_ObjectsGroups ObjGrp ON Obj.ID_Object = ObjGrp.ID_Object "
                        + " Where ObjGrp.ID_Dealer = '" + aID_Dealer + "' and ObjGrp.ID_Group = '" + lstUserGroup.SelectedValue + "'");

                Session["dsObjectsGroups"] = dsObjectsGroups;
                this.grvFunction.DataSource = dsObjectsGroups.Tables[0];
                this.grvFunction.DataBind();
            }
            catch(Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "BindItem", alert, true);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void DeleteItem(object sender, GridViewDeleteEventArgs e)
        {
            e.Cancel = true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    this.lblError.Visible = false;
                }
            }
            catch (Exception ex)
            {
                this.lblError.Visible = true;
                this.lblError.Text = ex.Message;
            }
        }

        protected void ddl_Module_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void lstUserGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadItem(""); // param is ID Dealer
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                
                // Get ds session
                DataSet dsObjectsGroups = (DataSet)Session["dsObjectsGroups"];

 
                if (dsObjectsGroups.HasChanges())
                {
                    DataSet dsChanges = dsObjectsGroups.GetChanges(DataRowState.Modified);


                    ArrayList sqlList = new ArrayList();
                    DatabaseParameters KeyParameters = new DatabaseParameters();
                    DatabaseParameters ValueParameters = new DatabaseParameters();

                    foreach (DataRow dr in dsChanges.Tables[0].Rows)
                    {
                        KeyParameters.Clear();
                        ValueParameters.Clear();

                        KeyParameters.Add(new DatabaseParameter("ID_Module", dr["ID_Module"].ToString()));
                        KeyParameters.Add(new DatabaseParameter("ID_Object", dr["ID_Object"].ToString()));
                        KeyParameters.Add(new DatabaseParameter("ID_Group", dr["ID_Group"].ToString()));
                        KeyParameters.Add(new DatabaseParameter("ID_Dealer", dr["ID_Dealer"].ToString()));

                        ValueParameters.Add(new DatabaseParameter("Read_Access", dr["Read_Access"].ToString().Equals("True") ? "1" : "0" ));
                        ValueParameters.Add(new DatabaseParameter("Add_Access_User", dr["Add_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("Delete_Access", dr["Delete_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("Modify_Access", dr["Modify_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("Print_Access", dr["Print_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("Post_Access", dr["Post_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("CloseOpenDoc_Access", dr["CloseOpenDoc_Access"].ToString().Equals("True") ? "1" : "0"));
                        ValueParameters.Add(new DatabaseParameter("UpdatedUser", "Admin")); // Hard code for test
                        ValueParameters.Add(new DatabaseParameter("UpdatedTime", DateTime.Now.ToString("MM/dd/yyyy")));

                        SqlHelper.UpdateCommand(KeyParameters, ValueParameters, "tbl_ObjectsGroups");
                        sqlList.Add(SqlHelper.SQL);
                    }

                    if (!SqlHelper.ExecuteQuery(sqlList, Data.ConnectionString))
                    {
                        string alert = "alert('Error: " + SqlHelper.ErrMsg + " ');";
                        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "btnUpdate_Click", alert, true);
                    }
                    else
                    {
                        this.lblError.Text = "Operation complete successful!";
                    }

                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }
    }
}